// 简单的MCP测试脚本
import fetch from 'node-fetch';

async function testMcpServer() {
  const baseUrl = 'http://localhost:3000/mcp';
  
  try {
    console.log('🔄 Testing MCP Server...');
    
    // 1. 测试初始化
    console.log('\n1. Testing initialize...');
    const initResponse = await fetch(baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/event-stream',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 'test-1',
        method: 'initialize',
        params: {
          protocolVersion: '2024-11-05',
          capabilities: {
            tools: {},
            resources: {},
          },
          clientInfo: {
            name: 'simple-test-client',
            version: '1.0.0',
          },
        },
      }),
    });
    
    if (!initResponse.ok) {
      throw new Error(`Initialize failed: ${initResponse.status} ${initResponse.statusText}`);
    }
    
    const contentType = initResponse.headers.get('content-type');
    console.log('📋 Response Content-Type:', contentType);
    
    let initResult;
    if (contentType && contentType.includes('text/event-stream')) {
      // Handle SSE response
      const text = await initResponse.text();
      console.log('📡 SSE Response:', text);
      // Parse SSE data lines
      const lines = text.split('\n');
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            initResult = JSON.parse(line.substring(6));
            break;
          } catch (e) {
            console.log('⚠️ Could not parse SSE data:', line);
          }
        }
      }
    } else {
      // Handle JSON response
      initResult = await initResponse.json();
    }
    
    console.log('✅ Initialize successful:', JSON.stringify(initResult, null, 2));
    
    // 提取会话ID - 检查响应头
    let sessionId = initResult.result?.sessionId;
    if (!sessionId) {
      // 尝试从响应头获取
      sessionId = initResponse.headers.get('mcp-session-id');
    }
    if (!sessionId) {
      console.log('⚠️ Available headers:');
      for (const [key, value] of initResponse.headers.entries()) {
        console.log(`  ${key}: ${value}`);
      }
      throw new Error('No session ID returned in response body or headers');
    }
    
    console.log(`📋 Session ID: ${sessionId}`);
    
    // 2. 测试列出工具
    console.log('\n2. Testing list tools...');
    const toolsResponse = await fetch(baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/event-stream',
        'mcp-session-id': sessionId,
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 'test-2',
        method: 'tools/list',
      }),
    });
    
    const toolsResult = await parseResponse(toolsResponse);
    console.log('✅ Tools list:', JSON.stringify(toolsResult, null, 2));
    
    // 3. 测试调用计算器工具
    console.log('\n3. Testing calculator tool...');
    const calcResponse = await fetch(baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/event-stream',
        'mcp-session-id': sessionId,
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 'test-3',
        method: 'tools/call',
        params: {
          name: 'calculator',
          arguments: {
            operation: 'add',
            a: 2,
            b: 3
          },
        },
      }),
    });
    
    const calcResult = await parseResponse(calcResponse);
    console.log('✅ Calculator result:', JSON.stringify(calcResult, null, 2));
    
    // 4. 测试列出资源
    console.log('\n4. Testing list resources...');
    const resourcesResponse = await fetch(baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/event-stream',
        'mcp-session-id': sessionId,
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 'test-4',
        method: 'resources/list',
      }),
    });
    
    const resourcesResult = await parseResponse(resourcesResponse);
    console.log('✅ Resources list:', JSON.stringify(resourcesResult, null, 2));
    
    console.log('\n🎉 All tests passed! MCP Server is working correctly.');
    
  } catch (error) {
    console.error('❌ Test failed:', error.message);
    process.exit(1);
  }
}

// 解析响应的辅助函数
async function parseResponse(response) {
  const contentType = response.headers.get('content-type');
  
  if (contentType && contentType.includes('text/event-stream')) {
    // Handle SSE response
    const text = await response.text();
    const lines = text.split('\n');
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        try {
          return JSON.parse(line.substring(6));
        } catch (e) {
          console.log('⚠️ Could not parse SSE data:', line);
        }
      }
    }
    throw new Error('No valid JSON data found in SSE response');
  } else {
    // Handle JSON response
    return await response.json();
  }
}

// 运行测试
testMcpServer();